<?php defined('SYSPATH') OR die('No direct access allowed.');

class stylesheet_Core
{
	static protected $styles = array();
    static protected $will_already_be_auto_rendered = false;

	static public function add($file)
	{
        if (is_array($file)) {
            self::$styles = arr::merge(self::$styles , $file);
        } else 
            if (!in_array($file, self::$styles))
                self::$styles[] = $file;
        //make sure the style are inserted in the header just before sending the page to the browser
        self::set_auto_render();
	}

	static public function render($print = FALSE)
	{
		$output = '';
		foreach (self::$styles as $style)
			$output .= html::stylesheet($style);

		if ($print)
			echo $output;

		return $output;
	}

    static public function set_auto_render() {
        //add a hook to the system.display Event. This event is called just before flushing content to the browser
        //only add the hook if we didn't set the hook already sometime earlier
        if (self::$will_already_be_auto_rendered == false) {
            Event::add('system.display', array('stylesheet_Core','render_style_in_head'));
            self::$will_already_be_auto_rendered = true;
        }
    }

    static public function render_style_in_head() {
        //insert the script tags just before the </head> tag
        //The to be flushed data is found in Event::$data
        Event::$data = str_replace("</head>", self::render() . " </head>", Event::$data);
    }

} // End stylesheet_Core

